﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using zjxj_repair.Bean;
using zjxj_repair.Bean.Model;
using LicenseContext = OfficeOpenXml.LicenseContext;

namespace zjxj_repair.Utils
{
    public static class Tools
    {
        public static void SetWatermark(this TextBox textBox, string watermarkText)
        {
            textBox.Text = watermarkText;
            textBox.ForeColor = Color.Gray;

            textBox.GotFocus += (s, e) =>
            {
                if (textBox.Text == watermarkText)
                {
                    textBox.Text = "";
                    textBox.ForeColor = Color.Black;
                }
            };

            textBox.LostFocus += (s, e) =>
            {
                if (string.IsNullOrWhiteSpace(textBox.Text))
                {
                    textBox.Text = watermarkText;
                    textBox.ForeColor = Color.Gray;
                }
            };
        }

        /// <summary>
        /// Soket客户端=>服务器
        /// </summary>
        /// <param name="toolBean"></param>
        /// <param name="hartStr"></param>
        /// <returns></returns>
        public static async Task<bool> SendToServer(ConfigModelBean item, string str, string toolName)
        {
            bool isSand = false;

            try
            {

                TcpClient toolBean = (TcpClient)item.ToolBean;

                if (!toolBean.Connected)
                    return false;

                NetworkStream stream = toolBean.GetStream();

                byte[] sendBuffer = Encoding.ASCII.GetBytes(str);

                await stream.WriteAsync(sendBuffer);

                ProduceLogText($"[拧紧枪通讯操作]-[{toolName}]发送指令[{str}]");

                // 缓存发送数据
                SoketSendList.AddData($"{toolName}_{str}");

                isSand = true;
            }
            catch
            {

            }

            return isSand;
        }

        public static int ToInt(this object data)
        {
            if (data == null)
            {
                return 0;
            }

            if (data is bool)
            {
                return ((bool)data) ? 1 : 0;
            }

            if (int.TryParse(data.ToString(), out var result))
            {
                return result;
            }

            try
            {
                return Convert.ToInt32(data.ToDouble(0));
            }
            catch (Exception)
            {
                return 0;
            }
        }

        public static double ToDouble(this object data, int digits)
        {
            return Math.Round(data.ToDouble(), digits, MidpointRounding.AwayFromZero);
        }

        public static double ToDouble(this object data)
        {
            if (data == null)
            {
                return 0.0;
            }

            double result;
            return double.TryParse(data.ToString(), out result) ? result : 0.0;
        }

        /// <summary>
        /// 生产日志消息处理
        /// </summary>
        /// <param name="message"></param>
        public static async void ProduceLogText(string message)
        {
            try
            {
                await AsyncLogger.WriteLogAsync("ProduceLog", message);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }
        }

        /// <summary>
        /// 设备日志消息处理
        /// </summary>
        /// <param name="message"></param>
        public static async void DeviceLogText(string message)
        {
            try
            {
                await AsyncLogger.WriteLogAsync("DeviceLog", message);
            }
            catch (Exception e)
            {
                Console.Write(e);
            }
        }

        /// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name="dic"></param>
        public static void DicToExcel(string key, Dictionary<string, string[]> dic)
        {
            try
            {
                if (dic != null && dic.Count > 0)
                {
                    // 创建一个文件保存对话框
                    using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                    {
                        // 设置默认文件扩展名和过滤器
                        saveFileDialog.Filter = "Excel 文件 (*.xlsx)|*.xlsx|所有文件 (*.*)|*.*";
                        saveFileDialog.FileName = $"{key}_{DateTime.Now.ToString("yyyyMMddhhmmss")}";
                        saveFileDialog.DefaultExt = "xlsx";
                        saveFileDialog.AddExtension = true;

                        // 如果用户选择了文件并点击了保存
                        if (saveFileDialog.ShowDialog() == DialogResult.OK)
                        {
                            // 获取用户选择的完整文件路径
                            string path = saveFileDialog.FileName;

                            // 设置 EPPlus 使用非商业许可证
                            ExcelPackage.License.SetNonCommercialPersonal("YYY");

                            ExcelPackage.License.SetNonCommercialOrganization("你的组织名称");

                            // 使用 EPPlus 创建 Excel 文件
                            using (var package = new ExcelPackage())
                            {
                                // 创建一个工作表
                                var worksheet = package.Workbook.Worksheets.Add(key);

                                // 初始化列索引
                                int columnIndex = 1;

                                foreach (var item in dic)
                                {
                                    // 初始化行索引
                                    int rowIndex = 2;

                                    // 设置表头
                                    worksheet.Cells[1, columnIndex].Value = item.Key;

                                    // 设置内容
                                    for (int i = 0; i <= item.Value.Length - 1; i++)
                                    {
                                        worksheet.Cells[rowIndex, columnIndex].Value = item.Value[i];

                                        rowIndex++;
                                    }

                                    // 列索引自增
                                    columnIndex++;
                                }

                                // 保存 Excel 文件到指定路径
                                FileInfo file = new FileInfo(path);
                                package.SaveAs(file);

                                MessageBox.Show("文件已导出");
                            }
                        }
                    }
                }
                else
                {
                    MessageBox.Show("不能导出空文件，请重新查询数据");
                }

            }
            catch (IOException ex)
            {
                MessageBox.Show($"写出文件异常: {ex.Message}");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"写出文件异常: {ex.Message}");
            }

        }

        /// <summary>
        /// 将DataGirdView控件中数据转换成Dic数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public static Dictionary<string, string[]> DataGirdViewToDic(DataGridView data)
        {
            // 初始化一个Dictionary
            Dictionary<string, string[]> dic = new Dictionary<string, string[]>();

            if (data != null)

                foreach (DataGridViewColumn column in data.Columns)
                {
                    if (column.Visible)
                    {
                        string key = column.Name;
                        List<string> valuesList = new List<string>();

                        foreach (DataGridViewRow row in data.Rows)
                        {
                            if (!row.IsNewRow) // 过滤掉新行
                            {
                                valuesList.Add(row.Cells[key].Value?.ToString() ?? string.Empty);
                            }
                        }

                        dic[key] = valuesList.ToArray(); // 转换为数组
                    }
                }

            return dic;
        }
    }
}
